<!--  -->
<template>
  <div class="app-main-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('message.shgl')" name="first">
        <div style="margin-bottom: 20px">
          <QueryForm
            v-model="filters"
            :query-form-config="queryFormConfig"
            @handleQuery="getList()"
            @clear="clear"
          />
          <el-button v-if="meta.indexOf('BraceletAdd') > -1" type="primary" @click="addBtn">{{
            $t('message.add')
          }}</el-button>
          <el-button type="danger" v-if="meta.indexOf('BraceletBatchDel') > -1" plain @click="plDelBtn">{{
            $t('message.pldel')
          }}</el-button>
          <el-button v-preventReClick v-if="meta.indexOf('BraceletUpload') > -1" @click="inBatch">{{
            $t('message.shdr')
          }}</el-button>
        </div>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
          @selection-change="handleSelectionChange"
        >
          >
          <el-table-column type="selection" width="55" />
          <el-table-column
            align="center"
            :label="$t('message.shbh')"
            prop="braceletName"
            min-width="100"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.shxpid')"
            prop="braceletCode"
            min-width="100"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.ssfl')"
            prop="depositName"
            min-width="100"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            :label="$t('message.sbzt')"
            min-width="80"
          >
            <template slot-scope="{ row }">
              <span
                class="lx"
                :class="{ act: row.state == 1 ? true : false }"
                >{{
                  row.state == 1 ? translate('ysy') : translate('wsy')
                }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('message.caozuo')"
            min-width="120"
          >
            <template slot-scope="scope">
              <div class="flex-cc">
                <el-button
                  v-preventReClick
                  type="text"
                  v-if="meta.indexOf('BraceletEdit') > -1"
                  @click="editBtn(scope.row)"
                  >{{ $t('message.edit') }}</el-button
                >
                <el-button
                  v-preventReClick
                  type="text"
                  class="secondColor"
                  v-if="meta.indexOf('BraceletDel') > -1"
                  @click="delRow(scope.row)"
                  >{{ $t('message.del') }}</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Paginations
          :total="total"
          :page="pagination.page"
          @SizeChange="pageSizeChange"
          @current-change="currentPageChange"
        />
        <el-dialog
          :title="DlogTit"
          :visible.sync="dialogVisible"
          width="35%"
          @close="cancelBra('ruleForm')"
        >
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item :label="translate('shbh')" prop="braceletName">
              <el-input
                v-model="ruleForm.braceletName"
                :placeholder="translate('qsr')"
                style="width: 80%"
              ></el-input>
            </el-form-item>
            <el-form-item :label="translate('shxpid')" prop="braceletCode">
              <el-input
                v-model="ruleForm.braceletCode"
                :placeholder="translate('qsr')"
                style="width: 80%"
              ></el-input>
            </el-form-item>
            <el-form-item :label="translate('ssfl')" prop="depositId">
              <el-select
                v-model="ruleForm.depositId"
                :placeholder="translate('qxz')"
              >
                <el-option
                  v-for="item in braSelect"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelBra('ruleForm')">{{
              translate('qx')
            }}</el-button>
            <el-button
              :loading="btnLoading"
              type="primary"
              @click="submitForm('ruleForm')"
              >{{ translate('qd') }}</el-button
            >
          </span>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane :label="$t('message.shjgl')" name="second">
        <braceleEquipment ref="braceleEquipmentRef" />
      </el-tab-pane>
      <el-tab-pane :label="$t('message.flgl')" name="third">
        <sortManage
          ref="sortManage"
          @add="sortManageAdd"
          @edit="sortManageEdit"
        />
        <braceletEdit ref="braceletEdit" @refresh="refreshfn" />
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :title="$t('message.pldr')"
      @close="cancelBracelet1('ruleForm1')"
      :visible.sync="isShow"
      width="500px"
    >
      <div class="el-upload__tip">
        <div class="mb10">{{ $t('message.drsm') }}</div>
        <div class="mb10">{{ $t('message.mbyqsm') }}</div>
        <div style="margin: 20px 0">
          <span>{{ $t('message.wjmb') }}</span>
          <span
            @click="downLoad"
            style="text-decoration: underline; color: #7190ff; cursor: pointer"
          >
            {{ $t('message.ajxzmb') }}</span
          >
        </div>
      </div>
      <el-form
        :model="ruleForm1"
        :rules="rules1"
        ref="ruleForm1"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="translate('ssfl')" prop="depositId">
          <el-select
            v-model="ruleForm1.depositId"
            :placeholder="translate('qxz')"
          >
            <el-option
              v-for="item in braSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-upload
        ref="excel-upload-input"
        :action="uploadFileUrl"
        :on-change="onChange"
        :data="uploadDatab"
        :auto-upload="true"
        accept=".xlsx, .xls"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-remove="removeFile"
        :file-list="fileList"
      >
        <span style="margin-left: 30px">{{ $t('message.scwj') }}</span>
        <el-button size="small" style="margin-left: 15px" plain>{{
          $t('message.xzwj')
        }}</el-button>
        <!-- <div slot="tip" class="el-upload__tip">
          <div class="mb10">{{ $t('message.mbyqsm') }}</div>
        </div> -->
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancelBracelet1('ruleForm1')">{{
          $t('message.qx')
        }}</el-button>
        <el-button
          v-preventReClick
          type="primary"
          :loading="loadinga"
          @click="submit('ruleForm1')"
          >{{ $t('message.qr') }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import QueryForm from '@/components/QueryForm'
import { queryFormConfig } from './config'
import {
  braceletList,
  braceletDelete,
  braceletEditt,
  braSlect,
  uploadFile,
  insertBra,
  insertBraCs,
  plBraceletDel
} from '@/api'
import sortManage from './sortManage'
import braceletEdit from './braceletEdit'
import braceleEquipment from './braceleEquipment'
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { sortManage, braceletEdit, braceleEquipment, QueryForm },
  data () {
    //这里存放数据
    return {
      activeName: 'first',
      queryFormConfig,
      filters: {},
      list: [],
      listLoading: false,
      pagination: {
        page: 1,
        rows: 10
      },
      list: [],
      total: 0,
      DlogTit: '',
      ruleForm: {},
      dialogVisible: false,
      rules: {
        braceletCode: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' }
        ],
        braceletName: [
          { required: true, message: this.translate('qsr'), trigger: 'blur' }
        ],
        depositId: [
          { required: true, message: this.translate('qxz'), trigger: 'change' }
        ]
      },
      btnLoading: false,
      braSelect: [],
      propName: '',
      isShow: false,
      uploadFileUrl: uploadFile,
      uploadDatab: {
        folder: 'MEALS_IMG'
      },
      fileList: [],
      ruleForm1: { depositId: '' },
      rules1: {
        depositId: [
          { required: true, message: this.translate('qxz'), trigger: 'change' }
        ]
      },
      loadinga: false,
      fileUrl: '',
      ids: [],
      meta:[]
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    handleSelectionChange (ROWS) {
      this.ids = ROWS.map(item => item.id)
    },
    plDelBtn () {
      if (!this.ids.length) return this.$message.error(this.translate('qxzdel'))
      this.$confirm(this.translate('isdel'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('qx'),
        type: 'warning'
      }).then(async () => {
        if (this.list.length === 1 && this.pagination.page > 1) {
          this.pagination.page--
        }
        const { errorCode } = await plBraceletDel({
          param: {
            ids: this.ids
          }
        })
        if (errorCode != '000000') return
        this.$message.success(this.translate('delcg'))
        this.getList()
      })
    },
    handleClick ({ name }) {
      if (name == 'first') {
        this.getList()
      } else if (name == 'second') {
        this.$refs.braceleEquipmentRef.getList()
      } else if (name == 'third') {
        this.$refs.sortManage.getList()
      }
    },
    sortManageAdd () {
      this.$refs.braceletEdit.show()
    },
    sortManageEdit (e) {
      this.$refs.braceletEdit.show(e)
    },
    refreshfn () {
      this.$refs.sortManage.getList()
    },
    getList () {
      this.listLoading = true
      const { pagination, filters } = this
      braceletList({
        pagination,
        param: { ...filters }
      })
        .then(({ recordList, totalCount }) => {
          this.listLoading = false
          this.list = recordList
          this.total = totalCount
        })
        .catch(res => {
          this.listLoading = false
        })
    },
    // 导入
    inBatch () {
      this.getRraSelect()
      this.isShow = true
    },
    submit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.fileUrl.length) {
            this.$message.error(this.$t('message.qxxzwj'))
            return
          }
          this.loadinga = true
          insertBraCs({
            param: {
              excelPath: this.fileUrl,
              depositId: this.ruleForm1.depositId
            }
          })
            .then(res => {
              this.$message.success(this.$t('message.pldrcg'))
              // this.isShow = false
              this.cancelBracelet1('ruleForm1')
              this.loadinga = false
              this.getList()
              this.fileList = []
            })
            .catch(err => {
              this.loadinga = false
            })
        }
      })
    },
    cancelBracelet1 (formName) {
      this.$refs[formName].resetFields()
      this.isShow = false
      this.ruleForm1 = {}
    },
    // 下载
    downLoad () {
      insertBra({ param: {} })
        .then(res => {
          if (res.errorCode === '000000') {
            window.open(res.record, '_blank')
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    onChange (file, list) {
      if (list.length > 1 && file.status !== 'fail') {
        list.splice(0, 1)
      } else if (file.status === 'fail') {
        list.splice(0, 1)
      }
    },
    // 文件上传成功时的钩子
    handleSuccess (res, file, fileList) {
      this.fileList = fileList
      this.fileUrl = file.response.showUrl
    },
    // 文件上传失败时的钩子
    handleError (err, file, fileList) {
      this.fileList = []
      this.fileUrl = ''
      this.$notify.error({
        title: this.$t('message.cw'),
        message: this.$t('message.wjscsb')
      })
      console.log(err, file, fileList)
    },
    // 文件移除
    removeFile (file, fileList) {
      console.log('移除')
      this.fileUrl = ''
    },
    // 添加设备
    addBtn () {
      this.getRraSelect()
      this.DlogTit = this.translate('add')
      this.dialogVisible = true
    },
    editBtn (row) {
      this.getRraSelect()
      this.DlogTit = this.translate('edit')
      this.ruleForm = { ...row }
      this.dialogVisible = true
    },
    // 删除设备
    delRow (row) {
      this.$confirm(this.translate('isdel'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('qx'),
        type: 'warning'
      }).then(async () => {
        if (this.list.length === 1 && this.pagination.page > 1) {
          this.pagination.page--
        }
        const { errorCode } = await braceletDelete({
          param: {
            id: row.id
          }
        })
        if (errorCode != '000000') return
        this.$message.success(this.translate('delcg'))
        this.getList()
      })
    },
    // 确认新增
    submitForm (formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          this.btnLoading = true
          if (this.ruleForm.id) {
            braceletEditt({
              param: {
                ...this.ruleForm
              }
            })
              .then(() => {
                this.btnLoading = false
                this.$message.success(this.translate('editcg'))
                this.getList()
                this.cancelBra('ruleForm')
              })
              .catch(() => {
                this.btnLoading = false
                return false
              })
          } else {
            braceletEditt({
              param: {
                ...this.ruleForm
              }
            })
              .then(() => {
                this.btnLoading = false
                this.$message.success(this.translate('addcg'))
                this.getList()
                this.cancelBra('ruleForm')
              })
              .catch(() => {
                this.btnLoading = false
                return false
              })
          }
        }
      })
    },
    // 取消
    cancelBra (formName) {
      this.$refs[formName].resetFields()
      this.dialogVisible = false
      this.ruleForm = {}
    },
    clear () {
      this.filters = {}
      this.getList()
    },
    pageSizeChange (val) {
      this.pagination.rows = val
      this.getList()
    },
    currentPageChange (val) {
      this.pagination.page = val
      this.getList()
    },
    // 获取下拉分类
    getRraSelect () {
      braSlect({
        param: {}
      }).then(({ recordList, totalCount }) => {
        this.braSelect = recordList
      })
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getList()
    this.meta = this.$route.meta.buttons || []
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {}
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.lx {
  color: rgba(255, 42, 42, 0.884);
}
.act {
  color: rgba(37, 150, 3, 0.897);
}
</style>
